package net.chowda.castcluster.jnlp;

import javax.swing.*;
import javax.swing.text.*;
import java.io.*;
import java.awt.*;

/**
 * JFrame for wrapping stderr and stdout
 */
public class GUIDialog extends JFrame {
    private final JTextPane textArea = new JTextPane();

    public GUIDialog() throws HeadlessException, IOException {
        super("CastCluster Console");

        JScrollPane pane = new JScrollPane(textArea);
        pane.setMinimumSize(new Dimension(600,400));
        pane.setPreferredSize(new Dimension(600,400));
        add(pane);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        // we're going to pipe stdout and stderr into a buffered reader.
        final PipedOutputStream out = new PipedOutputStream();
        final PrintStream pout = new PrintStream(out);
        System.setErr(pout);
        System.setOut(pout);
        final BufferedReader in = new BufferedReader(new InputStreamReader(new PipedInputStream(out)));

        // this thread sets the text of the JTextArea to the output of stdout 
        new Thread() {
            public void run() {
                try {
                    while(true) {
                        String line;
                        while((line=in.readLine())!=null) {
                            final String text = line;

                            SwingUtilities.invokeAndWait(new Runnable() {
                                public void run() {
                                    try {
                                        Document doc = textArea.getDocument();

                                        AttributeSet attrs = null;
                                        if(text.startsWith("*")) {
                                            StyleContext sc = StyleContext.getDefaultStyleContext();
                                            attrs = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Background, Color.YELLOW);
                                        }
                                        doc.insertString(doc.getLength(), text+'\n', attrs);
                                    } catch (BadLocationException e) {
                                        throw new RuntimeException(e);
                                    }
                                    scrollDown();
                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    throw new Error(e);
                }
            }
        }.start();

        pack();
    }

    private void scrollDown() {
        int pos = textArea.getDocument().getEndPosition().getOffset();
        textArea.getCaret().setDot(pos);
        textArea.requestFocus();
    }
}
